import { ref, reactive } from 'vue';
import { mqttService, topics } from './MQTTService';
import { userService } from './UserService';

// 棋子类型
export const ChessPieceType = {
  EMPTY: 0,       // 空位
  RED_KING: 1,    // 红帅
  RED_ADVISOR: 2, // 红士
  RED_ELEPHANT: 3,// 红相
  RED_HORSE: 4,   // 红马
  RED_CHARIOT: 5, // 红车
  RED_CANNON: 6,  // 红炮
  RED_PAWN: 7,    // 红兵
  BLACK_KING: 8,  // 黑将
  BLACK_ADVISOR: 9, // 黑士
  BLACK_ELEPHANT: 10,// 黑象
  BLACK_HORSE: 11,   // 黑马
  BLACK_CHARIOT: 12, // 黑车
  BLACK_CANNON: 13,  // 黑炮
  BLACK_PAWN: 14,    // 黑卒
};

// 游戏状态枚举
export const ChessGameStatus = {
  IDLE: 'idle',           // 空闲状态
  MATCHING: 'matching',   // 正在匹配
  PLAYING: 'playing',     // 游戏中
  GAME_OVER: 'game_over', // 游戏结束
};

// 棋子阵营
export const ChessCamp = {
  RED: 'red',   // 红方
  BLACK: 'black' // 黑方
};

class ChessGameService {
  constructor() {
    // 游戏状态
    this.status = ref(ChessGameStatus.IDLE);
    
    // 游戏房间信息
    this.room = reactive({
      roomId: null,
      players: [],
      currentTurn: null,
      winner: null,
      startTime: null,
      lastMoveTime: null,
    });
    
    // 棋盘状态 (10x9)
    this.boardSize = { rows: 10, cols: 9 };
    this.board = ref(Array(this.boardSize.rows).fill().map(() => Array(this.boardSize.cols).fill(ChessPieceType.EMPTY)));
    
    // 当前玩家的阵营
    this.myCamp = ref(null);
    
    // 计时器
    this.turnTimer = ref(60); // 象棋每回合60秒
    this.timerInterval = null;
    
    // 锁定状态（防止多线程问题）
    this.isLocked = false;
    
    // 匹配超时计时器
    this.matchingTimeoutId = null;
  }
  
  // 初始化游戏服务
  init() {
    console.log('初始化象棋游戏服务');
  }
  
  // 开始匹配
  async startMatching() {
    if (this.status.value !== ChessGameStatus.IDLE) {
      console.warn('当前状态不允许开始匹配');
      return false;
    }
    
    if (this.isLocked) {
      console.warn('操作被锁定，请稍后再试');
      return false;
    }
    
    try {
      this.isLocked = true;
      
      // 确保MQTT已连接
      if (!mqttService.connected.value) {
        console.log('MQTT未连接，尝试连接...');
        try {
          await mqttService.connect();
        } catch (error) {
          console.error('MQTT连接失败:', error);
          this.isLocked = false;
          return false;
        }
      }
      
      // 更新状态为匹配中
      this.status.value = ChessGameStatus.MATCHING;
      
      // 发送匹配请求
      const userInfo = userService.getUserInfo();
      console.log('发送匹配请求:', userInfo);
      
      try {
        await mqttService.publish(topics.GAME_MATCHING, {
          type: 'request_chess_match',
          userId: userInfo.userId,
          username: userInfo.username,
          timestamp: new Date().getTime(),
        });
        console.log('匹配请求已发送');
      } catch (error) {
        console.error('发送匹配请求失败:', error);
        this.status.value = ChessGameStatus.IDLE;
        this.isLocked = false;
        return false;
      }
      
      // 设置匹配超时（30秒）
      this.matchingTimeoutId = setTimeout(() => {
        if (this.status.value === ChessGameStatus.MATCHING) {
          this.cancelMatching();
          console.log('匹配超时');
        }
      }, 30000);
      
      return true;
    } finally {
      this.isLocked = false;
    }
  }
  
  // 取消匹配
  cancelMatching() {
    if (this.status.value !== ChessGameStatus.MATCHING) {
      return false;
    }
    
    // 清除匹配超时计时器
    if (this.matchingTimeoutId) {
      clearTimeout(this.matchingTimeoutId);
      this.matchingTimeoutId = null;
    }
    
    // 发送取消匹配请求
    const userInfo = userService.getUserInfo();
    mqttService.publish(topics.GAME_MATCHING, {
      type: 'cancel_chess_match',
      userId: userInfo.userId,
      timestamp: new Date().getTime(),
    });
    
    // 更新状态为空闲
    this.status.value = ChessGameStatus.IDLE;
    
    return true;
  }
  
  // 处理匹配成功
  handleMatchSuccess(roomData) {
    console.log('处理匹配成功:', roomData);
    
    // 如果已经在游戏中，则不重复处理
    if (this.status.value === ChessGameStatus.PLAYING) {
      console.log('已经在游戏中，不重复处理匹配成功');
      return true;
    }
    
    // 清除匹配超时计时器
    if (this.matchingTimeoutId) {
      clearTimeout(this.matchingTimeoutId);
      this.matchingTimeoutId = null;
    }
    
    // 更新房间信息
    this.room.roomId = roomData.roomId;
    this.room.players = roomData.players;
    this.room.currentTurn = roomData.currentTurn;
    this.room.startTime = roomData.startTime;
    this.room.lastMoveTime = roomData.startTime;
    
    // 确定自己的阵营
    const myUserId = userService.userId.value;
    const myPlayerInfo = roomData.players.find(player => player.userId === myUserId);
    
    if (myPlayerInfo) {
      this.myCamp.value = myPlayerInfo.camp;
      console.log(`我的阵营: ${this.myCamp.value}`);
    } else {
      console.error('在房间玩家列表中找不到自己');
      return false;
    }
    
    // 订阅房间主题
    const roomTopic = `${topics.GAME_ROOM}${this.room.roomId}_chess`;
    mqttService.subscribe(roomTopic);
    
    // 初始化棋盘
    this.initializeBoard();
    
    // 更新状态为游戏中
    this.status.value = ChessGameStatus.PLAYING;
    
    // 启动计时器
    this.startTurnTimer();
    
    console.log('匹配成功处理完成，游戏开始');
    return true;
  }
  
  // 初始化棋盘
  initializeBoard() {
    console.log('初始化象棋棋盘...');
    // 创建空棋盘
    const newBoard = Array(this.boardSize.rows).fill().map(() => Array(this.boardSize.cols).fill(ChessPieceType.EMPTY));
    
    // 放置红方棋子
    // 第一行
    newBoard[9][0] = ChessPieceType.RED_CHARIOT;
    newBoard[9][1] = ChessPieceType.RED_HORSE;
    newBoard[9][2] = ChessPieceType.RED_ELEPHANT;
    newBoard[9][3] = ChessPieceType.RED_ADVISOR;
    newBoard[9][4] = ChessPieceType.RED_KING;
    newBoard[9][5] = ChessPieceType.RED_ADVISOR;
    newBoard[9][6] = ChessPieceType.RED_ELEPHANT;
    newBoard[9][7] = ChessPieceType.RED_HORSE;
    newBoard[9][8] = ChessPieceType.RED_CHARIOT;
    
    // 炮
    newBoard[7][1] = ChessPieceType.RED_CANNON;
    newBoard[7][7] = ChessPieceType.RED_CANNON;
    
    // 兵
    newBoard[6][0] = ChessPieceType.RED_PAWN;
    newBoard[6][2] = ChessPieceType.RED_PAWN;
    newBoard[6][4] = ChessPieceType.RED_PAWN;
    newBoard[6][6] = ChessPieceType.RED_PAWN;
    newBoard[6][8] = ChessPieceType.RED_PAWN;
    
    // 放置黑方棋子
    // 第一行
    newBoard[0][0] = ChessPieceType.BLACK_CHARIOT;
    newBoard[0][1] = ChessPieceType.BLACK_HORSE;
    newBoard[0][2] = ChessPieceType.BLACK_ELEPHANT;
    newBoard[0][3] = ChessPieceType.BLACK_ADVISOR;
    newBoard[0][4] = ChessPieceType.BLACK_KING;
    newBoard[0][5] = ChessPieceType.BLACK_ADVISOR;
    newBoard[0][6] = ChessPieceType.BLACK_ELEPHANT;
    newBoard[0][7] = ChessPieceType.BLACK_HORSE;
    newBoard[0][8] = ChessPieceType.BLACK_CHARIOT;
    
    // 炮
    newBoard[2][1] = ChessPieceType.BLACK_CANNON;
    newBoard[2][7] = ChessPieceType.BLACK_CANNON;
    
    // 卒
    newBoard[3][0] = ChessPieceType.BLACK_PAWN;
    newBoard[3][2] = ChessPieceType.BLACK_PAWN;
    newBoard[3][4] = ChessPieceType.BLACK_PAWN;
    newBoard[3][6] = ChessPieceType.BLACK_PAWN;
    newBoard[3][8] = ChessPieceType.BLACK_PAWN;
    
    // 更新棋盘
    this.board.value = newBoard;
    console.log('棋盘初始化完成');
  }
  
  // 移动棋子
  movePiece(fromRow, fromCol, toRow, toCol) {
    // 检查是否轮到自己行动
    const myUserId = userService.userId.value;
    if (this.room.currentTurn !== myUserId) {
      console.warn('当前不是您的回合');
      return false;
    }
    
    // 检查起始位置是否有自己的棋子
    const piece = this.board.value[fromRow][fromCol];
    if (piece === ChessPieceType.EMPTY) {
      console.warn('起始位置没有棋子');
      return false;
    }
    
    // 检查是否是自己的棋子
    const isRedPieceFlag = piece >= ChessPieceType.RED_KING && piece <= ChessPieceType.RED_PAWN;
    const isBlackPieceFlag = piece >= ChessPieceType.BLACK_KING && piece <= ChessPieceType.BLACK_PAWN;
    
    if ((this.myCamp.value === ChessCamp.RED && !isRedPieceFlag) ||
        (this.myCamp.value === ChessCamp.BLACK && !isBlackPieceFlag)) {
      console.warn('不能移动对方的棋子');
      return false;
    }
    
      // 检查移动是否合法
      if (!this.isValidMove(fromRow, fromCol, toRow, toCol)) {
          console.warn('移动不合法');
          return false;
      }
      // 检查将帅对面
      const isRedPieceKing = piece >= ChessPieceType.RED_KING && piece <= ChessPieceType.RED_PAWN;
      if ((piece === ChessPieceType.RED_KING || piece === ChessPieceType.BLACK_KING) &&
          this.isKingFacingKing(toRow, toCol, isRedPieceKing)) {
          console.warn('将帅不能对面');
          return false;
      }
    // 执行移动
    const capturedPiece = this.board.value[toRow][toCol];
    
    // 发送移动消息
    const roomTopic = `${topics.GAME_ROOM}${this.room.roomId}_chess`;
    mqttService.publish(roomTopic, {
      type: 'move_piece',
      userId: myUserId,
      from: { row: fromRow, col: fromCol },
      to: { row: toRow, col: toCol },
      piece: piece,
      captured: capturedPiece,
      timestamp: new Date().getTime(),
    });
    
    // 更新本地棋盘
    this.board.value[toRow][toCol] = piece;
    this.board.value[fromRow][fromCol] = ChessPieceType.EMPTY;
    
    // 检查是否将军或将死
    // 新增：如果有一方的将/帅被吃掉，直接判定胜负
    const redKingAlive = this.board.value.some(row => row.includes(ChessPieceType.RED_KING));
    const blackKingAlive = this.board.value.some(row => row.includes(ChessPieceType.BLACK_KING));
    if (!redKingAlive || !blackKingAlive) {
      // 有一方的将/帅被吃掉
      const winnerId = !redKingAlive
        ? (this.room.players.find(p => p.camp === ChessCamp.BLACK)?.userId)
        : (this.room.players.find(p => p.camp === ChessCamp.RED)?.userId);
      this.handleGameOver(winnerId);
      return true;
    }
    if (this.isCheckmate()) {
      this.handleGameOver(myUserId);
      return true;
    }
    
    // 切换回合
    const nextPlayer = this.room.players.find(player => player.userId !== myUserId);
    if (nextPlayer) {
      this.room.currentTurn = nextPlayer.userId;
    }
    
    // 重置计时器
    this.resetTurnTimer();
    
    return true;
  }
  
    // 检查移动是否合法
    isValidMove(fromRow, fromCol, toRow, toCol) {
        // 检查起始和目标位置是否相同
        if (fromRow === toRow && fromCol === toCol) return false;

        // 获取起始位置棋子
        const piece = this.board.value[fromRow][fromCol];
        // 获取目标位置棋子
        const targetPiece = this.board.value[toRow][toCol];

        // 检查目标位置是否有己方棋子
        const isRedPieceFlag = piece >= ChessPieceType.RED_KING && piece <= ChessPieceType.RED_PAWN;
        const isTargetRed = targetPiece >= ChessPieceType.RED_KING && targetPiece <= ChessPieceType.RED_PAWN;
        if (targetPiece !== ChessPieceType.EMPTY && ((isRedPieceFlag && isTargetRed) || (!isRedPieceFlag && !isTargetRed))) {
            return false; // 不能吃己方棋子
        }

        // 根据不同棋子类型检查走法
        switch (piece) {
            case ChessPieceType.RED_KING:
            case ChessPieceType.BLACK_KING:
                return this.isKingMoveValid(fromRow, fromCol, toRow, toCol, isRedPieceFlag);
            case ChessPieceType.RED_ADVISOR:
            case ChessPieceType.BLACK_ADVISOR:
                return this.isAdvisorMoveValid(fromRow, fromCol, toRow, toCol, isRedPieceFlag);
            case ChessPieceType.RED_ELEPHANT:
            case ChessPieceType.BLACK_ELEPHANT:
                return this.isElephantMoveValid(fromRow, fromCol, toRow, toCol, isRedPieceFlag);
            case ChessPieceType.RED_HORSE:
            case ChessPieceType.BLACK_HORSE:
                return this.isHorseMoveValid(fromRow, fromCol, toRow, toCol);
            case ChessPieceType.RED_CHARIOT:
            case ChessPieceType.BLACK_CHARIOT:
                return this.isChariotMoveValid(fromRow, fromCol, toRow, toCol);
            case ChessPieceType.RED_CANNON:
            case ChessPieceType.BLACK_CANNON:
                return this.isCannonMoveValid(fromRow, fromCol, toRow, toCol);
            case ChessPieceType.RED_PAWN:
            case ChessPieceType.BLACK_PAWN:
                return this.isPawnMoveValid(fromRow, fromCol, toRow, toCol, isRedPieceFlag);
            default:
                return false;
        }
    }

    // 帅/将走法验证
    isKingMoveValid(fromRow, fromCol, toRow, toCol, isRed) {
        // 帅/将只能在九宫格内移动
        const minRow = isRed ? 7 : 0;
        const maxRow = isRed ? 9 : 2;
        const minCol = 3;
        const maxCol = 5;

        if (toRow < minRow || toRow > maxRow || toCol < minCol || toCol > maxCol) {
            return false;
        }

        // 帅/将只能走一步
        const rowDiff = Math.abs(toRow - fromRow);
        const colDiff = Math.abs(toCol - fromCol);
        if (!((rowDiff === 1 && colDiff === 0) || (rowDiff === 0 && colDiff === 1))) {
            return false;
        }

        // 检查将帅对面
        if (this.isKingFacingKing(toRow, toCol, isRed)) {
            return false;
        }

        return true;
    }

    // 士/仕走法验证
    isAdvisorMoveValid(fromRow, fromCol, toRow, toCol, isRed) {
        // 士/仕只能在九宫格内移动
        const minRow = isRed ? 7 : 0;
        const maxRow = isRed ? 9 : 2;
        const minCol = 3;
        const maxCol = 5;

        if (toRow < minRow || toRow > maxRow || toCol < minCol || toCol > maxCol) {
            return false;
        }

        // 士/仕只能斜走一格
        const rowDiff = Math.abs(toRow - fromRow);
        const colDiff = Math.abs(toCol - fromCol);
        return rowDiff === 1 && colDiff === 1;
    }

    // 象/相走法验证
    isElephantMoveValid(fromRow, fromCol, toRow, toCol, isRed) {
        // 象/相不能过河
        if ((isRed && toRow < 5) || (!isRed && toRow > 4)) {
            return false;
        }

        // 象/相走田字
        const rowDiff = Math.abs(toRow - fromRow);
        const colDiff = Math.abs(toCol - fromCol);
        if (rowDiff !== 2 || colDiff !== 2) {
            return false;
        }

        // 检查象眼是否被塞
        const eyeRow = fromRow + (toRow - fromRow) / 2;
        const eyeCol = fromCol + (toCol - fromCol) / 2;
        return this.board.value[eyeRow][eyeCol] === ChessPieceType.EMPTY;
    }

    // 马走法验证
    isHorseMoveValid(fromRow, fromCol, toRow, toCol) {
        // 马走日字
        const rowDiff = Math.abs(toRow - fromRow);
        const colDiff = Math.abs(toCol - fromCol);
        if (!((rowDiff === 1 && colDiff === 2) || (rowDiff === 2 && colDiff === 1))) {
            return false;
        }

        // 检查绊马脚
        if (rowDiff === 2) {
            const legRow = fromRow + (toRow - fromRow) / 2;
            if (this.board.value[legRow][fromCol] !== ChessPieceType.EMPTY) {
                return false;
            }
        } else {
            const legCol = fromCol + (toCol - fromCol) / 2;
            if (this.board.value[fromRow][legCol] !== ChessPieceType.EMPTY) {
                return false;
            }
        }

        return true;
    }

    // 车走法验证
    isChariotMoveValid(fromRow, fromCol, toRow, toCol) {
        // 车走直线
        if (fromRow !== toRow && fromCol !== toCol) {
            return false;
        }

        // 检查路径是否有棋子阻挡
        if (fromRow === toRow) {
            // 横向移动
            const minCol = Math.min(fromCol, toCol);
            const maxCol = Math.max(fromCol, toCol);
            for (let col = minCol + 1; col < maxCol; col++) {
                if (this.board.value[fromRow][col] !== ChessPieceType.EMPTY) {
                    return false;
                }
            }
        } else {
            // 纵向移动
            const minRow = Math.min(fromRow, toRow);
            const maxRow = Math.max(fromRow, toRow);
            for (let row = minRow + 1; row < maxRow; row++) {
                if (this.board.value[row][fromCol] !== ChessPieceType.EMPTY) {
                    return false;
                }
            }
        }

        return true;
    }

    // 炮走法验证
    isCannonMoveValid(fromRow, fromCol, toRow, toCol) {
        // 炮走直线
        if (fromRow !== toRow && fromCol !== toCol) {
            return false;
        }

        // 目标位置是否有棋子
        const hasTarget = this.board.value[toRow][toCol] !== ChessPieceType.EMPTY;
        let obstacleCount = 0;

        // 检查路径
        if (fromRow === toRow) {
            // 横向移动
            const minCol = Math.min(fromCol, toCol);
            const maxCol = Math.max(fromCol, toCol);
            for (let col = minCol + 1; col < maxCol; col++) {
                if (this.board.value[fromRow][col] !== ChessPieceType.EMPTY) {
                    obstacleCount++;
                }
            }
        } else {
            // 纵向移动
            const minRow = Math.min(fromRow, toRow);
            const maxRow = Math.max(fromRow, toRow);
            for (let row = minRow + 1; row < maxRow; row++) {
                if (this.board.value[row][fromCol] !== ChessPieceType.EMPTY) {
                    obstacleCount++;
                }
            }
        }

        // 炮吃子需要一个炮架，移动不需要
        return hasTarget ? obstacleCount === 1 : obstacleCount === 0;
    }

    // 兵/卒走法验证
    isPawnMoveValid(fromRow, fromCol, toRow, toCol, isRed) {
        const rowDiff = toRow - fromRow;
        const colDiff = Math.abs(toCol - fromCol);

        // 兵/卒不能后退
        if ((isRed && rowDiff > 0) || (!isRed && rowDiff < 0)) {
            return false;
        }

        // 兵/卒只能走一格
        if (Math.abs(rowDiff) + colDiff !== 1) {
            return false;
        }

        // 没过河不能左右移动
        const hasCrossedRiver = (isRed && fromRow <= 4) || (!isRed && fromRow >= 5);
        if (!hasCrossedRiver && colDiff > 0) {
            return false;
        }

        return true;
    }

    // 检查将帅是否对面
    isKingFacingKing(kingRow, kingCol, isRedKing) {
        const opponentKingType = isRedKing ? ChessPieceType.BLACK_KING : ChessPieceType.RED_KING;
        let opponentKingRow = -1;

        // 找到对方将/帅
        for (let row = 0; row < this.boardSize.rows; row++) {
            if (this.board.value[row][kingCol] === opponentKingType) {
                opponentKingRow = row;
                break;
            }
        }

        if (opponentKingRow === -1) return false;

        // 检查将帅之间是否有棋子
        const minRow = Math.min(kingRow, opponentKingRow);
        const maxRow = Math.max(kingRow, opponentKingRow);
        for (let row = minRow + 1; row < maxRow; row++) {
            if (this.board.value[row][kingCol] !== ChessPieceType.EMPTY) {
                return false;
            }
        }

        return true;
    }
  
    // 检查是否将军或将死
    isCheckmate() {
        // 1. 找到当前玩家的将/帅位置
        const isRedTurn = this.myCamp.value === ChessCamp.RED;
        const kingType = isRedTurn ? ChessPieceType.RED_KING : ChessPieceType.BLACK_KING;
        let kingRow = -1, kingCol = -1;

        // 查找将/帅位置
        for (let row = 0; row < this.boardSize.rows; row++) {
            for (let col = 0; col < this.boardSize.cols; col++) {
                if (this.board.value[row][col] === kingType) {
                    kingRow = row;
                    kingCol = col;
                    break;
                }
            }
            if (kingRow !== -1) break;
        }

        if (kingRow === -1) return false; // 找不到将/帅，不应该发生

        // 2. 检查是否被将军
        if (!this.isKingInCheck(kingRow, kingCol, isRedTurn)) {
            return false; // 未被将军
        }

        // 3. 检查是否有逃脱的可能
        return this.isNoEscape(kingRow, kingCol, isRedTurn);
    }

    // 检查将/帅是否被将军
    isKingInCheck(kingRow, kingCol, isRedKing) {
        const opponentPieceTypes = isRedKing
            ? [8, 9, 10, 11, 12, 13, 14] // 黑方棋子
            : [1, 2, 3, 4, 5, 6, 7]; // 红方棋子

        // 检查对方所有棋子是否能攻击到将/帅
        for (let row = 0; row < this.boardSize.rows; row++) {
            for (let col = 0; col < this.boardSize.cols; col++) {
                const piece = this.board.value[row][col];
                if (opponentPieceTypes.includes(piece)) {
                    // 临时交换位置，检查是否能移动到将/帅位置
                    const originalPiece = this.board.value[kingRow][kingCol];
                    this.board.value[kingRow][kingCol] = ChessPieceType.EMPTY;

                    const isValid = this.isValidMove(row, col, kingRow, kingCol);

                    // 恢复原位
                    this.board.value[kingRow][kingCol] = originalPiece;

                    if (isValid) {
                        return true; // 将军
                    }
                }
            }
        }
        return false;
    }

    // 检查是否没有逃脱的可能（将死）
    isNoEscape(kingRow, kingCol, isRedKing) {
        // 尝试将/帅移动到所有可能的位置
        const directions = [
            [-1, 0], [1, 0], [0, -1], [0, 1] // 上下左右
        ];

        for (const [dr, dc] of directions) {
            const newRow = kingRow + dr;
            const newCol = kingCol + dc;

            // 检查新位置是否在九宫内
            const minRow = isRedKing ? 7 : 0;
            const maxRow = isRedKing ? 9 : 2;
            const minCol = 3;
            const maxCol = 5;

            if (newRow < minRow || newRow > maxRow || newCol < minCol || newCol > maxCol) {
                continue;
            }

            // 检查新位置是否有己方棋子
            const targetPiece = this.board.value[newRow][newCol];
            const isTargetRed = targetPiece >= ChessPieceType.RED_KING && targetPiece <= ChessPieceType.RED_PAWN;
            if (targetPiece !== ChessPieceType.EMPTY && ((isRedKing && isTargetRed) || (!isRedKing && !isTargetRed))) {
                continue;
            }

            // 尝试移动将/帅
            const originalPiece = this.board.value[newRow][newCol];
            this.board.value[newRow][newCol] = isRedKing ? ChessPieceType.RED_KING : ChessPieceType.BLACK_KING;
            this.board.value[kingRow][kingCol] = ChessPieceType.EMPTY;

            // 检查移动后是否仍被将军
            const stillInCheck = this.isKingInCheck(newRow, newCol, isRedKing);

            // 恢复原位
            this.board.value[kingRow][kingCol] = isRedKing ? ChessPieceType.RED_KING : ChessPieceType.BLACK_KING;
            this.board.value[newRow][newCol] = originalPiece;

            if (!stillInCheck) {
                return false; // 可以逃脱，未将死
            }
        }

        // 尝试吃掉攻击的棋子或挡住攻击
        return this.cannotBlockOrCapture(kingRow, kingCol, isRedKing);
    }

    // 检查是否无法通过吃子或挡子解围
    cannotBlockOrCapture(kingRow, kingCol, isRedKing) {
        // 找到所有攻击将/帅的棋子
        const attackerPositions = this.findAttackers(kingRow, kingCol, isRedKing);
        if (attackerPositions.length === 0) return true;

        // 如果有多个攻击者，无法同时挡住
        if (attackerPositions.length > 1) return true;

        // 单个攻击者：尝试吃掉或挡住
        const [attackerRow, attackerCol] = attackerPositions[0];
        const attackerPiece = this.board.value[attackerRow][attackerCol];

        // 1. 尝试吃掉攻击者
        if (this.canCaptureAttacker(attackerRow, attackerCol, isRedKing)) {
            return false;
        }

        // 2. 尝试挡住攻击路径
        if (this.canBlockAttack(kingRow, kingCol, attackerRow, attackerCol, isRedKing)) {
            return false;
        }

        return true; // 无法解围，将死
    }

    // 其他辅助方法（findAttackers, canCaptureAttacker, canBlockAttack）省略，完整实现需要添加
  
  // 处理游戏结束
  handleGameOver(winnerId) {
    // 如果已经是游戏结束状态，则不重复处理
    if (this.status.value === ChessGameStatus.GAME_OVER) {
      console.log('游戏已经结束，不重复处理');
      return false;
    }
    
    console.log(`处理游戏结束，获胜者ID: ${winnerId}`);
    
    // 更新游戏状态
    this.status.value = ChessGameStatus.GAME_OVER;
    
    // 更新获胜者
    this.room.winner = winnerId;
    
    // 停止计时器
    this.stopTurnTimer();
    
    // 发送游戏结束消息
    if (this.room.roomId) {
      const roomTopic = `${topics.GAME_ROOM}${this.room.roomId}_chess`;
      console.log(`发送游戏结束消息到主题: ${roomTopic}`);
      
      mqttService.publish(roomTopic, {
        type: 'game_over',
        winnerId: winnerId,
        timestamp: new Date().getTime(),
      });
      
      // 取消订阅房间主题
      setTimeout(() => {
        console.log(`取消订阅房间主题: ${roomTopic}`);
        mqttService.unsubscribe(roomTopic);
      }, 1000);
    } else {
      console.warn('房间ID不存在，无法发送游戏结束消息');
    }
    
    return true;
  }
  
  // 开始新游戏
  startNewGame() {
    console.log('开始新象棋游戏');
    
    // 如果有房间ID，取消订阅房间主题
    if (this.room.roomId) {
      const roomTopic = `${topics.GAME_ROOM}${this.room.roomId}_chess`;
      console.log(`取消订阅房间主题: ${roomTopic}`);
      mqttService.unsubscribe(roomTopic);
    }
    
    // 重置游戏状态
    this.status.value = ChessGameStatus.IDLE;
    
    // 重置房间信息
    this.room.roomId = null;
    this.room.players = [];
    this.room.currentTurn = null;
    this.room.winner = null;
    this.room.startTime = null;
    this.room.lastMoveTime = null;
    
    // 重置棋盘
    this.board.value = Array(this.boardSize.rows).fill().map(() => Array(this.boardSize.cols).fill(ChessPieceType.EMPTY));
    
    // 重置阵营
    this.myCamp.value = null;
    
    // 停止计时器
    this.stopTurnTimer();
    
    console.log('象棋游戏已重置');
    return true;
  }
  
  // 处理对方移动棋子
  handlePieceMoved(moveData) {
    const { from, to, piece } = moveData;
    
    // 更新棋盘
    this.board.value[to.row][to.col] = piece;
    this.board.value[from.row][from.col] = ChessPieceType.EMPTY;
    
    // 更新当前回合
    const nextPlayer = this.room.players.find(player => player.userId !== moveData.userId);
    if (nextPlayer) {
      this.room.currentTurn = nextPlayer.userId;
    }
    
    // 更新最后移动时间
    this.room.lastMoveTime = moveData.timestamp;
    
    // 重置计时器
    this.resetTurnTimer();
    
    return true;
  }
  
  // 启动回合计时器
  startTurnTimer() {
    this.turnTimer.value = 60; // 象棋每回合60秒
    
    this.stopTurnTimer();  // 确保之前的计时器已停止
    
    this.timerInterval = setInterval(() => {
      if (this.turnTimer.value > 0) {
        this.turnTimer.value--;
      } else {
        // 时间用完，如果是当前玩家的回合，则判负
        const myUserId = userService.userId.value;
        if (this.room.currentTurn === myUserId) {
          // 找到对手ID
          const opponent = this.room.players.find(player => player.userId !== myUserId);
          if (opponent) {
            this.handleGameOver(opponent.userId);
          }
        }
      }
    }, 1000);
  }
  
  // 重置回合计时器
  resetTurnTimer() {
    this.turnTimer.value = 60; // 象棋每回合60秒
  }
  
  // 停止回合计时器
  stopTurnTimer() {
    if (this.timerInterval) {
      clearInterval(this.timerInterval);
      this.timerInterval = null;
    }
  }
  
  // 处理MQTT消息
  handleMQTTMessage(topic, message) {
    console.log(`处理象棋MQTT消息: 主题=${topic}, 类型=${message.type || '未知'}`);
    
    // 如果已经是游戏结束状态，除了match_success消息外，忽略其他消息
    if (this.status.value === ChessGameStatus.GAME_OVER && 
        !(topic === topics.GAME_MATCHING && message.type === 'chess_match_success')) {
      console.log('游戏已结束，忽略消息');
      return;
    }
    
    // 匹配相关消息
    if (topic === topics.GAME_MATCHING) {
      if (message.type === 'chess_match_success') {
        this.handleMatchSuccess(message.room);
      }
    }
    
    // 游戏房间相关消息
    if (topic.includes(`${topics.GAME_ROOM}`) && topic.endsWith('_chess')) {
      switch (message.type) {
        case 'move_piece':
          this.handlePieceMoved(message);
          break;
        case 'game_over':
          // 避免重复处理游戏结束
          if (this.status.value !== ChessGameStatus.GAME_OVER) {
            this.handleGameOver(message.winnerId);
          } else {
            console.log('已经处于游戏结束状态，忽略game_over消息');
          }
          break;
        case 'player_leave':
          // 处理玩家离开
          if (this.status.value === ChessGameStatus.PLAYING) {
            const opponent = this.room.players.find(player => player.userId !== message.userId);
            if (opponent) {
              this.handleGameOver(opponent.userId);
            }
          } else {
            console.log('不在游戏中状态，忽略player_leave消息');
          }
          break;
        default:
          console.warn(`未知的消息类型: ${message.type}`);
      }
    }
  }
  
  // 离开游戏
  leaveGame() {
    if (this.status.value === ChessGameStatus.PLAYING) {
      // 发送玩家离开消息
      const roomTopic = `${topics.GAME_ROOM}${this.room.roomId}_chess`;
      mqttService.publish(roomTopic, {
        type: 'player_leave',
        userId: userService.userId.value,
        timestamp: new Date().getTime(),
      });
      
      // 取消订阅房间主题
      mqttService.unsubscribe(roomTopic);
    }
    
    // 重置游戏
    this.startNewGame();
    
    return true;
  }
}

// 导出单例
export const chessGameService = new ChessGameService();